package com.xjscrm.console.service.customer.group.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.trigger.MicaTriggerConversationMembersPushMsg;
import com.uzai.mobile.collect.api.dto.trigger.MicaTriggerConversationPushMsg;
import com.uzai.mobile.collect.api.dto.trigger.group.*;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.DeviceTypeEnum;
import com.xjscrm.common.enums.MerConfigKeyEnum;
import com.xjscrm.common.enums.MerConfigTypeEnum;
import com.xjscrm.common.enums.RedisCacheKeyEnum;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.vo.wwgroupconfig.WwGroupConfig;
import com.xjscrm.console.chat.frame.recv.RPullGroupMemberMsg;
import com.xjscrm.console.chat.frame.recv.RPullGroupMsg;
import com.xjscrm.console.common.util.MyExcelUtil;
import com.xjscrm.console.entity.ChatTalkSession;
import com.xjscrm.console.entity.MerchatChildDeviceRelation;
import com.xjscrm.console.mapper.*;
import com.xjscrm.console.mq.producer.SendMsgProducer;
import com.xjscrm.console.param.BaseDto;
import com.xjscrm.console.param.group.*;
import com.xjscrm.console.param.materialLibrary.MaterialConfigGroupQuery;
import com.xjscrm.console.param.wwCustomer.CustomerQuery;
import com.xjscrm.console.param.wwDevice.WwDeviceQuery;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionService;
import com.xjscrm.console.service.customer.group.WwGroupService;
import com.xjscrm.console.vo.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class WwGroupServiceImpl implements WwGroupService {

    @Autowired
    private WwGroupMapper wwGroupMapper;

    @Autowired
    private WwGroupMemberMapper groupMemberMapper;

    @Autowired
    private WwGroupTagsRelationMapper wwGroupTagsRelationMapper;

    @Autowired
    private WwDeviceMapper wwDeviceMapper;

    @Autowired
    private WwGroupTagMapper wwGroupTagMapper;

    @Autowired
    private WwGroupMemberMapper wwGroupMemberMapper;

    @Autowired
    private WwCustomerMapper wwCustomerMapper;

    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SendMsgProducer sendMsgProducer;
    @Autowired
    @Lazy
    private ChatTalkSessionService chatTalkSessionService;

    @Autowired
    private MaterialConfigGroupMapper materialConfigGroupMapper;

    @Autowired
    private MerchatChildDeviceRelationMapper merchatChildDeviceRelationMapper;

    @Autowired
    private SyncGroupJobMapper syncGroupJobMapper;

    @Override
    public MyPageInfo<WwGroupVo> getWwGroupList(WwGroupQuery wwGroupQuery) {
        if (wwGroupQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        //如果群标签ID参数不为空，根据群标签找到对应的群微信ID
        List<Long> ids=new ArrayList<>();
        if (wwGroupQuery.getGroupTagId() != null) {
            WwGroupTagsRelationQuery wwGroupTagsRelationQuery = new WwGroupTagsRelationQuery();
            wwGroupTagsRelationQuery.setMerId(wwGroupQuery.getMerId());
            wwGroupTagsRelationQuery.setTagId(wwGroupQuery.getGroupTagId());
            List<WwGroupTagsRelation> wwGroupTagsRelationList = wwGroupTagsRelationMapper.getWwGroupTagsRelationList(wwGroupTagsRelationQuery);
            if (wwGroupTagsRelationList != null && !wwGroupTagsRelationList.isEmpty()) {
                for (WwGroupTagsRelation wwGroupTagsRelation:wwGroupTagsRelationList) {
                    WwGroup wwGroup = wwGroupMapper.getByGroupWxid(wwGroupTagsRelation.getGroupWxid(), wwGroupTagsRelation.getDeviceId(), wwGroupTagsRelation.getMerId());
                    if(wwGroup!=null){
                        ids.add(wwGroup.getId());
                    }
                }
            }

            if (ids.isEmpty()) {
                return new MyPageInfo<>(null);
            } else {
                wwGroupQuery.setIds(ids);
            }
        }else if(wwGroupQuery.getParentGroupTagId() != null){
            WwGroupTagQuery wwGroupTagQuery=new WwGroupTagQuery();
            wwGroupTagQuery.setMerId(wwGroupQuery.getMerId());
            wwGroupTagQuery.setPid(wwGroupQuery.getParentGroupTagId());
            List<WwGroupTagsVo> wwGroupTagsVoList = wwGroupTagMapper.getWwGroupTag(wwGroupTagQuery);

            if(wwGroupTagsVoList==null||wwGroupTagsVoList.isEmpty()){
                return new MyPageInfo<>(null);
            }
            List<Long> groupTagIds = wwGroupTagsVoList.stream().map(WwGroupTagsVo::getId).distinct().collect(Collectors.toList());

            WwGroupTagsRelationQuery wwGroupTagsRelationQuery = new WwGroupTagsRelationQuery();
            wwGroupTagsRelationQuery.setMerId(wwGroupQuery.getMerId());
            wwGroupTagsRelationQuery.setTagIds(groupTagIds);
            List<WwGroupTagsRelation> wwGroupTagsRelationList = wwGroupTagsRelationMapper.getWwGroupTagsRelationList(wwGroupTagsRelationQuery);
            if (wwGroupTagsRelationList != null && !wwGroupTagsRelationList.isEmpty()) {
                for (WwGroupTagsRelation wwGroupTagsRelation:wwGroupTagsRelationList) {
                    WwGroup wwGroup = wwGroupMapper.getByGroupWxid(wwGroupTagsRelation.getGroupWxid(), wwGroupTagsRelation.getDeviceId(), wwGroupTagsRelation.getMerId());
                    if(wwGroup!=null){
                        ids.add(wwGroup.getId());
                    }
                }
            }

            if (ids.isEmpty()) {
                return new MyPageInfo<>(null);
            } else {
                wwGroupQuery.setIds(ids);
            }

        }

        if (!StringUtils.isBlank(wwGroupQuery.getDeviceKeyword())) {
            WwDeviceQuery wwDeviceQuery = new WwDeviceQuery();
            wwDeviceQuery.setMerId(wwGroupQuery.getMerId());
            wwDeviceQuery.setKeyword(wwGroupQuery.getDeviceKeyword());
            List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
            if (wwDeviceList != null && !wwDeviceList.isEmpty()) {
                List<Long> collect = wwDeviceList.stream().map(WwDeviceVo::getId).distinct().collect(Collectors.toList());
                if (collect != null && !collect.isEmpty()) {
                    wwGroupQuery.setDeviceUniqueIds(collect);
                } else {
                    return new MyPageInfo<>(null);
                }
            } else {
                return new MyPageInfo<>(null);
            }
        }

        //群主机器人ID
        if (wwGroupQuery.getGroupMemberIdentitys() != null) {
            WwDevice wwDevice = wwDeviceMapper.getById(wwGroupQuery.getDeviceUniqueId(), wwGroupQuery.getMerId());
            if (wwDevice == null || wwDevice.getDeviceId() == null) {
                return new MyPageInfo<>(null);
            }
            if(wwGroupQuery.getGroupMemberIdentitys()==0){
                wwGroupQuery.setCreateWxid(wwDevice.getDeviceId());
            }
            if(wwGroupQuery.getGroupMemberIdentitys()==1){
                wwGroupQuery.setAdminWxid(wwDevice.getDeviceId());
            }
            if(wwGroupQuery.getGroupMemberIdentitys()==2){
                WwGroupMemberQuery wwGroupMemberQuery=new WwGroupMemberQuery();
                wwGroupMemberQuery.setMerId(wwDevice.getMerId());
                wwGroupMemberQuery.setWxid(wwDevice.getDeviceId());
                List<WwGroupMemberVo> wwGroupMemberList = wwGroupMemberMapper.getWwGroupMemberList(wwGroupMemberQuery);
                if(wwGroupMemberList==null||wwGroupMemberList.isEmpty()){
                    return new MyPageInfo<>(null);
                }
                //排除群主和群管理员
                List<String> excludeGroupWxIds=new ArrayList<>();
                for (WwGroupMemberVo wwGroupMemberVo:wwGroupMemberList) {
                    WwGroupQuery query=new WwGroupQuery();
                    query.setMerId(wwGroupMemberVo.getMerId());
                    query.setGroupWxids(Arrays.asList(wwGroupMemberVo.getGroupWxid()));
                    query.setCreateWxid(wwGroupMemberVo.getWxid());
                    List<WwGroupVo> wwGroupList = wwGroupMapper.getWwGroupList(query);
                    if(wwGroupList!=null&&!wwGroupList.isEmpty()){
                        excludeGroupWxIds.add(wwGroupMemberVo.getGroupWxid());
                        continue;
                    }

                    WwGroupQuery query1=new WwGroupQuery();
                    query1.setMerId(wwGroupMemberVo.getMerId());
                    query1.setGroupWxids(Arrays.asList(wwGroupMemberVo.getGroupWxid()));
                    query1.setAdminWxid(wwGroupMemberVo.getWxid());
                    List<WwGroupVo> wwGroupList1 = wwGroupMapper.getWwGroupList(query1);
                    if(wwGroupList1!=null&&!wwGroupList1.isEmpty()){
                        excludeGroupWxIds.add(wwGroupMemberVo.getGroupWxid());
                    }

                }

                List<String> collect = wwGroupMemberList.stream().map(WwGroupMemberVo::getGroupWxid).distinct().collect(Collectors.toList());

                if(excludeGroupWxIds.isEmpty()){
                    wwGroupQuery.setGroupWxids(collect);
                }else {
                    List<String> collect1 = collect.stream().filter(it -> !excludeGroupWxIds.contains(it)).collect(Collectors.toList());
                    if (collect1.isEmpty()) {
                        return new MyPageInfo<>(null);
                    }
                    wwGroupQuery.setGroupWxids(collect1);
                }

            }

        }

        //筛选素材群 排出已选择的群
        if (wwGroupQuery.getMaterialConfigGroup() != null && wwGroupQuery.getMaterialConfigGroup() == 1) {
            MaterialConfigGroupQuery materialConfigGroupQuery = new MaterialConfigGroupQuery();
            materialConfigGroupQuery.setMerId(wwGroupQuery.getMerId());
            List<MaterialConfigGroupVo> materialConfigGroupList = materialConfigGroupMapper.getMaterialConfigGroupList(materialConfigGroupQuery);
            if (materialConfigGroupList != null && !materialConfigGroupList.isEmpty()) {
                List<String> excludeGroupWxIds = materialConfigGroupList.stream().map(MaterialConfigGroupVo::getGroupWxid).distinct().collect(Collectors.toList());
                wwGroupQuery.setExcludeGroupWxIds(excludeGroupWxIds);
            }
        }

        //如果是子账号，只能查看自己账号所管理的 机器人
        if (wwGroupQuery.getOperatorType() != null && wwGroupQuery.getOperatorType() == 1) {
            if (wwGroupQuery.getChildId() == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID为空");
            }
            List<MerchatChildDeviceRelation> merchatChildDeviceRelationList = merchatChildDeviceRelationMapper.selectByStaffId(wwGroupQuery.getMerId(), wwGroupQuery.getChildId());
            if (merchatChildDeviceRelationList == null || merchatChildDeviceRelationList.isEmpty()) {
                return new MyPageInfo<>(null);
            }
            List<Long> deviceUniqueIds = merchatChildDeviceRelationList.stream().map(MerchatChildDeviceRelation::getRobotId).distinct().collect(Collectors.toList());
            wwGroupQuery.setChildOwnDeviceUniqueIds(deviceUniqueIds);
        }



        String orderBy = OrderByUtil.getOrderBy(wwGroupQuery.getOrderByField(), wwGroupQuery.isAsc());
        PageHelper.startPage(wwGroupQuery.getCurrent(), wwGroupQuery.getSize(), orderBy);
        List<WwGroupVo> wwGroupVoList = wwGroupMapper.getWwGroupList(wwGroupQuery);
        if (wwGroupVoList == null) {
            return new MyPageInfo<>(null);
        }

        for (WwGroupVo wwGroupVo : wwGroupVoList) {
            try {
                //获取机器人微信昵称
                WwDevice wwDevice = wwDeviceMapper.getById(wwGroupVo.getDeviceUniqueId(), wwGroupVo.getMerId());
                if (wwDevice != null) {
                    wwGroupVo.setDeviceName(wwDevice.getDeviceName());
                    wwGroupVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                }

                //获取群标签名
                List<String> tagNames = new ArrayList<>();
                WwGroupTagsRelationQuery wwGroupTagsRelationQuery = new WwGroupTagsRelationQuery();
                wwGroupTagsRelationQuery.setMerId(wwGroupVo.getMerId());
                wwGroupTagsRelationQuery.setGroupWxid(wwGroupVo.getGroupWxid());
                List<WwGroupTagsRelation> wwGroupTagsRelationList = wwGroupTagsRelationMapper.getWwGroupTagsRelationList(wwGroupTagsRelationQuery);
                if (wwGroupTagsRelationList != null && !wwGroupTagsRelationList.isEmpty()) {
                    List<Long> tagIds = wwGroupTagsRelationList.stream().map(WwGroupTagsRelation::getTagId).distinct().collect(Collectors.toList());
                    if (!tagIds.isEmpty()) {
                        for (Long tagId : tagIds) {
                            WwGroupTags wwGroupTags = wwGroupTagMapper.getById(tagId, wwGroupVo.getMerId());
                            if (wwGroupTags != null) {
                                tagNames.add(wwGroupTags.getName());
                            }
                        }
                    }
                }

                if (!tagNames.isEmpty()) {
                    wwGroupVo.setTagNames(tagNames);
                }

                //获取群主头像，群主昵称
                WwGroupMember member = wwGroupMemberMapper.getByGroupWxIdAndWxid(wwGroupVo.getGroupWxid(), wwGroupVo.getCreateWxid(), wwGroupVo.getMerId());
                if (member != null) {
                    wwGroupVo.setCreateUserName(member.getNick());
                    wwGroupVo.setCreateHimg(member.getHimg());
                }

                //获取群人数
                Integer memberTotal= (Integer) redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.GROUP_MEMBER_COUNT.getKey(), wwGroupVo.getGroupWxid()));
                if(memberTotal!=null){
                    wwGroupVo.setMemberTotal(memberTotal);
                }



            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return new MyPageInfo<>(wwGroupVoList);
    }

    @Override
    public Object getWwGroupDetail(WwGroupDto wwGroupDto) {
        if (wwGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (wwGroupDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        WwGroup wwGroup = wwGroupMapper.getById(wwGroupDto.getId(), wwGroupDto.getMerId());
        if (wwGroup == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "客户群不存在");
        }
        WwGroupVo wwGroupVo = new WwGroupVo();
        BeanUtil.copyProperties(wwGroup, wwGroupVo);

        try {
            //获取机器人微信昵称
            WwDevice wwDevice = wwDeviceMapper.getById(wwGroupVo.getDeviceUniqueId(), wwGroupVo.getMerId());
            if (wwDevice != null) {
                wwGroupVo.setDeviceName(wwGroupVo.getDeviceName());
            }

            //获取群标签名
            List<String> tagNames = new ArrayList<>();
            WwGroupTagsRelationQuery wwGroupTagsRelationQuery = new WwGroupTagsRelationQuery();
            wwGroupTagsRelationQuery.setMerId(wwGroupVo.getMerId());
            wwGroupTagsRelationQuery.setGroupWxid(wwGroupVo.getGroupWxid());
            List<WwGroupTagsRelation> wwGroupTagsRelationList = wwGroupTagsRelationMapper.getWwGroupTagsRelationList(wwGroupTagsRelationQuery);
            if (wwGroupTagsRelationList != null && !wwGroupTagsRelationList.isEmpty()) {
                List<Long> tagIds = wwGroupTagsRelationList.stream().map(WwGroupTagsRelation::getTagId).distinct().collect(Collectors.toList());
                if (!tagIds.isEmpty()) {
                    for (Long tagId : tagIds) {
                        WwGroupTags wwGroupTags = wwGroupTagMapper.getById(tagId, wwGroupVo.getMerId());
                        if (wwGroupTags != null) {
                            tagNames.add(wwGroupTags.getName());
                        }
                    }
                }
            }

            if (!tagNames.isEmpty()) {
                wwGroupVo.setTagNames(tagNames);
            }

            //获取群主微信昵称
            List<String> adminUserNames = new ArrayList<>();
            WwGroupMemberQuery wwGroupMemberQuery = new WwGroupMemberQuery();
            wwGroupMemberQuery.setMerId(wwGroupVo.getMerId());
            wwGroupMemberQuery.setGroupWxid(wwGroupVo.getGroupWxid());
            wwGroupMemberQuery.setWxid(wwGroup.getCreateWxid());
            List<WwGroupMemberVo> wwGroupMemberVoList = wwGroupMemberMapper.getWwGroupMemberList(wwGroupMemberQuery);
            if (wwGroupMemberVoList != null && wwGroupMemberVoList.size() == 1) {
                wwGroupVo.setCreateUserName(wwGroupMemberVoList.get(0).getNick());
            }

            //获取群成员微信昵称
            ObjectMapper objectMapper = new ObjectMapper();
            List<String> list = objectMapper.readValue(wwGroup.getAdminWxIds(), new TypeReference<List<String>>(){});
            if(!list.isEmpty()){
                WwGroupMemberQuery wwGroupMemberQuery1 = new WwGroupMemberQuery();
                wwGroupMemberQuery1.setMerId(wwGroupVo.getMerId());
                wwGroupMemberQuery1.setGroupWxid(wwGroupVo.getGroupWxid());
                wwGroupMemberQuery1.setWxids(list);
                List<WwGroupMemberVo> wwGroupMemberVoList1 = wwGroupMemberMapper.getWwGroupMemberList(wwGroupMemberQuery1);
                if (wwGroupMemberVoList1 != null && !wwGroupMemberVoList1.isEmpty()) {
                    adminUserNames = wwGroupMemberVoList1.stream().map(WwGroupMemberVo::getNick).collect(Collectors.toList());
                }
                if (!adminUserNames.isEmpty()) {
                    wwGroupVo.setAdminUserNames(adminUserNames);
                }
            }


            //获取群人数
            Integer memberTotal= (Integer) redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.GROUP_MEMBER_COUNT.getKey(), wwGroupVo.getGroupWxid()));
            if(memberTotal!=null){
                wwGroupVo.setMemberTotal(memberTotal);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return wwGroupVo;
    }

    @Override
    public void groupMemberUpdateGroupName(WwGroupDto wwGroupDto) {
        if (wwGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (wwGroupDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (wwGroupDto.getUpdateGroupName() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        WwGroup wwGroup = wwGroupMapper.getById(wwGroupDto.getId(), wwGroupDto.getMerId());
        if (wwGroup == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该客户群不存在");
        }

        wwGroup.setUpdateGroupName(wwGroup.getUpdateGroupName());
        int i = wwGroupMapper.updateWwGroup(wwGroup);

        if (i == 1) {
            //推送mq消息
        }


    }

    public long[] getStartAndEndOfDayTimestamps(long timestamp) {
        LocalDate date = Instant.ofEpochSecond(timestamp).atZone(ZoneId.systemDefault()).toLocalDate();
        long startOfDayTimestamp = date.atStartOfDay(ZoneId.systemDefault()).toEpochSecond();
        long endOfDayTimestamp = date.atTime(LocalTime.MAX).atZone(ZoneId.systemDefault()).toEpochSecond();
        return new long[]{startOfDayTimestamp, endOfDayTimestamp};
    }

    @Override
    public Object getGroupMemberList(WwGroupMemberQuery wwGroupMemberQuery) {
        if (wwGroupMemberQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        if (wwGroupMemberQuery.getStartTime() != null) {
            long[] startAndEndOfDayTimestamps = getStartAndEndOfDayTimestamps(wwGroupMemberQuery.getStartTime());
            wwGroupMemberQuery.setStartTime((int) startAndEndOfDayTimestamps[0]);
            wwGroupMemberQuery.setEndTime((int) startAndEndOfDayTimestamps[1]);
        }


        //查询出通讯录中所有的客户
        if (wwGroupMemberQuery.getIfFriend() != null) {
            CustomerQuery customerQuery = new CustomerQuery();
            customerQuery.setMerId(wwGroupMemberQuery.getMerId());

            List<WwCustomerVo> customerVoList = wwCustomerMapper.getCustomer(customerQuery);
            if (customerVoList != null && !customerVoList.isEmpty()) {
                List<String> customerWxids = customerVoList.stream().map(WwCustomerVo::getWxid).distinct().collect(Collectors.toList());
                wwGroupMemberQuery.setCustomerWxids(customerWxids);
            } else {
                return new MyPageInfo<>(null);
            }
        }

        String orderBy = OrderByUtil.getOrderBy(wwGroupMemberQuery.getOrderByField(), wwGroupMemberQuery.isAsc());
        PageHelper.startPage(wwGroupMemberQuery.getCurrent(), wwGroupMemberQuery.getSize(), orderBy);
        List<WwGroupMemberVo> wwGroupMemberVoList = wwGroupMemberMapper.getWwGroupMemberList(wwGroupMemberQuery);
        if (wwGroupMemberVoList != null) {
            for (WwGroupMemberVo wwGroupMemberVo : wwGroupMemberVoList) {

                //获取邀请人微信昵称
                WwCustomer wwCustomerMapperByWxId = wwCustomerMapper.getByWxId(wwGroupMemberVo.getInviterWxid(), wwGroupMemberVo.getMerId());

                if (wwCustomerMapperByWxId != null) {
                    wwGroupMemberVo.setInviterWxName(wwCustomerMapperByWxId.getName());
                }
                //设置是否加好友
                if (wwGroupMemberQuery.getIfFriend() != null) {
                    wwGroupMemberVo.setIfFriend(wwGroupMemberQuery.getIfFriend());
                } else {
                    WwCustomer wwCustomer = wwCustomerMapper.getByWxId(wwGroupMemberVo.getWxid(), wwGroupMemberVo.getMerId());
                    if (wwCustomer != null) {
                        wwGroupMemberVo.setIfFriend(1);
                    } else {
                        wwGroupMemberVo.setIfFriend(0);
                    }
                }

                //设置添加场景
                wwGroupMemberVo.setSceneDesc();

            }
        }

        return new MyPageInfo<>(wwGroupMemberVoList);
    }

    @Override
    public void addWwGroupConfig(WwGroupConfigDto wwGroupConfigDto) {
        if (wwGroupConfigDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        //查询配置表是否有改配置
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(wwGroupConfigDto.getMerId(), MerConfigKeyEnum.WWGROUP_CONFIG.getValue());
        if (merBaseConfig != null) {
            merBaseConfig.setVal(JSONObject.toJSONString(wwGroupConfigDto.getWwGroupConfig()));
            merBaseConfigMapper.update(merBaseConfig);
        } else {
            MerBaseConfig config = new MerBaseConfig();
            int time = DateUtil.getTime();
            config.setId(IdWorker.getId());
            config.setMerId(wwGroupConfigDto.getMerId());
            config.setType(MerConfigTypeEnum.DEVICES.getValue());
            config.setKey(MerConfigKeyEnum.WWGROUP_CONFIG.getValue());
            config.setVal(JSONObject.toJSONString(wwGroupConfigDto.getWwGroupConfig()));
            config.setCreateTime(time);
            config.setUpdateTime(time);
            merBaseConfigMapper.insert(config);
        }

        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.WWGROUP_CONFIG.getKey(), wwGroupConfigDto.getMerId()), JSONObject.toJSONString(wwGroupConfigDto.getWwGroupConfig()));
    }

    @Override
    public Object getWwGroupConfig(BaseDto baseDto) {
        if (baseDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        String key = String.format(RedisCacheKeyEnum.WWGROUP_CONFIG.getKey(), baseDto.getMerId());
        if (redisTemplate.hasKey(key)) {
            WwGroupConfig wwGroupConfig = JSONObject.parseObject(redisTemplate.opsForValue().get(key).toString(), WwGroupConfig.class);
            return wwGroupConfig;
        } else {
            MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(baseDto.getMerId(), MerConfigKeyEnum.WWGROUP_CONFIG.getValue());
            if (merBaseConfig != null) {
                WwGroupConfig wwGroupConfig = JSONObject.parseObject(merBaseConfig.getVal(), WwGroupConfig.class);
                return wwGroupConfig;
            } else {
//                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该客户群配置");
                return null;
            }
        }
    }

    @Override
    public void updateGroupName(BatchUpdateGroupNameDto batchUpdateGroupNameDto) {
        if (batchUpdateGroupNameDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchUpdateGroupNameDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
//        if (batchUpdateGroupNameDto.getBeginNumber() == null) {
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
//        }
        //查询出客户群
        WwGroup wwGroup = wwGroupMapper.getById(batchUpdateGroupNameDto.getId(), batchUpdateGroupNameDto.getMerId());
        String newContent = "";
        if (wwGroup != null) {
            newContent = Tools.getStr(batchUpdateGroupNameDto.getContent());
            newContent = newContent.replace("[当前群名]", Tools.getStr(wwGroup.getGroupName()))
                    .replace("[数字编号]", Tools.getStr(batchUpdateGroupNameDto.getBeginNumber()==null?null:batchUpdateGroupNameDto.getBeginNumber().toString()));
            wwGroup.setGroupName(newContent);
            wwGroupMapper.updateWwGroup(wwGroup);
        } else {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "客户群不存在");
        }

        WwDevice wwDevice = wwDeviceMapper.getById(wwGroup.getDeviceUniqueId(), batchUpdateGroupNameDto.getMerId());
        if (wwDevice == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人不存在");
        }

        MicaTriggerGroupSetNameMsg micaTriggerGroupSetNameMsg = new MicaTriggerGroupSetNameMsg();
        micaTriggerGroupSetNameMsg.setMessageId(wwGroup.getId());
        micaTriggerGroupSetNameMsg.setGroupId(wwGroup.getGroupWxid());
        micaTriggerGroupSetNameMsg.setNewGroupName(newContent);
        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerGroupSetNameMsg, MicaTriggerType.TRIGGER_GROUP_SET_NAME);
        micaTriggerDto.setMerId(wwDevice.getMerId());
        micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
        micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);

    }

    @Override
    public void updateGroupNameReplace(BatchUpdateGroupNameDto batchUpdateGroupNameDto) {
        if (batchUpdateGroupNameDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchUpdateGroupNameDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (StringUtils.isBlank(batchUpdateGroupNameDto.getKeyword())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (StringUtils.isBlank(batchUpdateGroupNameDto.getReplaceword())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        WwGroup wwGroup = wwGroupMapper.getById(batchUpdateGroupNameDto.getId(), batchUpdateGroupNameDto.getMerId());
        if (wwGroup != null) {
            String groupName = wwGroup.getGroupName().replaceAll(batchUpdateGroupNameDto.getKeyword(), batchUpdateGroupNameDto.getReplaceword());
            wwGroup.setGroupName(groupName);
            wwGroupMapper.updateWwGroup(wwGroup);


            WwDevice wwDevice = wwDeviceMapper.getById(wwGroup.getDeviceUniqueId(), batchUpdateGroupNameDto.getMerId());
            if (wwDevice == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人不存在");
            }

            //发送mq 指令
            MicaTriggerGroupSetNameMsg micaTriggerGroupSetNameMsg = new MicaTriggerGroupSetNameMsg();
            micaTriggerGroupSetNameMsg.setMessageId(wwGroup.getId());
            micaTriggerGroupSetNameMsg.setGroupId(wwGroup.getGroupWxid());
            micaTriggerGroupSetNameMsg.setNewGroupName(groupName);
            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerGroupSetNameMsg, MicaTriggerType.TRIGGER_GROUP_SET_NAME);
            micaTriggerDto.setMerId(wwDevice.getMerId());
            micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
            micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);


        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleGroup(WwGroupDto wwGroupDto) {
        if (wwGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (wwGroupDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }

        WwGroup wwGroup = wwGroupMapper.getById(wwGroupDto.getId(), wwGroupDto.getMerId());


        if (wwGroup != null) {
            WwDevice wwDevice = wwDeviceMapper.getById(wwGroup.getDeviceUniqueId(), wwGroup.getMerId());
            if (wwDevice == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人不存在");
            }

            //删除客户群和群标签的关系
            WwGroupTagsRelationQuery wwGroupTagsRelationQuery = new WwGroupTagsRelationQuery();
            wwGroupTagsRelationQuery.setMerId(wwGroup.getMerId());
            wwGroupTagsRelationQuery.setGroupWxid(wwGroup.getGroupWxid());
            wwGroupTagsRelationQuery.setDeviceId(wwGroup.getDeviceId());
            List<WwGroupTagsRelation> wwGroupTagsRelationList = wwGroupTagsRelationMapper.getWwGroupTagsRelationList(wwGroupTagsRelationQuery);
            if (wwGroupTagsRelationList != null && !wwGroupTagsRelationList.isEmpty()) {
                wwGroupTagsRelationList.forEach(it -> wwGroupTagsRelationMapper.deleById(it.getId(), it.getMerId()));
            }

            //删除群成员
            WwGroupMemberQuery wwGroupMemberQuery = new WwGroupMemberQuery();
            wwGroupMemberQuery.setMerId(wwGroup.getMerId());
            wwGroupMemberQuery.setGroupWxid(wwGroup.getGroupWxid());
            List<WwGroupMemberVo> wwGroupMemberList = wwGroupMemberMapper.getWwGroupMemberList(wwGroupMemberQuery);
            if (wwGroupMemberList != null && !wwGroupMemberList.isEmpty()) {
                List<String> collect = wwGroupMemberList.stream().map(WwGroupMemberVo::getWxid).distinct().collect(Collectors.toList());
                wwGroupMemberList.forEach(it -> wwGroupMemberMapper.deleById(it.getId(), it.getMerId()));

                //发送删除群成员指令
                MicaTriggerGroupKickMsg micaTriggerGroupKickMsg = new MicaTriggerGroupKickMsg();
                micaTriggerGroupKickMsg.setMessageId(IdWorker.getId());
                micaTriggerGroupKickMsg.setGroupId(wwGroup.getGroupWxid());
                micaTriggerGroupKickMsg.setWxIds(String.join(";", collect));

                MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerGroupKickMsg, MicaTriggerType.TRIGGER_GROUP_KICK);
                micaTriggerDto.setMerId(wwDevice.getMerId());
                micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
                micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
                sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
            }


            //删除客户群
            wwGroupMapper.deleById(wwGroup.getId(), wwGroup.getMerId());


            //发送mq指令
            MicaTriggerGroupExitMsg micaTriggerGroupExitMsg = new MicaTriggerGroupExitMsg();
            micaTriggerGroupExitMsg.setMessageId(wwGroup.getId());
            micaTriggerGroupExitMsg.setGroupId(wwGroup.getGroupWxid());

            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerGroupExitMsg, MicaTriggerType.TRIGGER_GROUP_EXIT);
            micaTriggerDto.setMerId(wwDevice.getMerId());
            micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
            micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);


        }
    }

    @Override
    public void exportWwGroup(WwGroupQuery wwGroupQuery, HttpServletResponse response) {
        if (wwGroupQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (wwGroupQuery.getFieldList() == null && wwGroupQuery.getFieldList().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        wwGroupQuery.setCurrent(1);
        wwGroupQuery.setSize(10000);
        MyPageInfo<WwGroupVo> wwGroupList = getWwGroupList(wwGroupQuery);
        if (wwGroupList.getRecords() != null && !wwGroupList.getRecords().isEmpty()) {
            List<WwGroupVo> records = wwGroupList.getRecords();
            records.forEach(it -> {
                it.setGroupCreateTimeDesc();
                it.setUpdateGroupNameDesc();
                it.setTagNamesDesc();
            });

            List<String> FieldsList = wwGroupQuery.getFieldList().stream().map(SheetHeader::getDataIndex).distinct().collect(Collectors.toList());

            Map<String, String> replacements = new HashMap<>();
            replacements.put("groupCreateTime", "groupCreateTimeDesc");
            replacements.put("tagNames", "tagNamesDesc");
            replacements.put("updateGroupName", "updateGroupNameDesc");
            List<String> Fields = FieldsList.stream()
                    .map(str -> replacements.getOrDefault(str, str))
                    .collect(Collectors.toList());


            List<String> titles = wwGroupQuery.getFieldList().stream().map(SheetHeader::getTitle).distinct().collect(Collectors.toList());

            // 使用Stream筛选匹配的字段
            List<Object> matchedObjects = records.stream()
                    .map(obj -> {
                        Map<String, Object> matchedFields = new HashMap<>();
                        Fields.forEach(field -> {
                            try {
                                Field objField = obj.getClass().getDeclaredField(field);
                                objField.setAccessible(true);
                                matchedFields.put(field, objField.get(obj));
                            } catch (NoSuchFieldException | IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        });
                        return matchedFields;
                    })
                    .filter(fieldsMap -> fieldsMap.size() == Fields.size())
                    .collect(Collectors.toList());

            try {
                MyExcelUtil.exportExcel(response, titles, matchedObjects, Fields);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


    // 创建自定义注解

    @Override
    public Page<WwGroup> pageFromChat(@MerId Long merId, RPullGroupMsg content) {

        Page<WwGroup> page = new Page<>(content.getCurrent(), content.getSize());

        List<WwGroup> customerList = wwGroupMapper.pageByCondition(page, content);
        if (ObjectUtils.isEmpty(customerList)) {
            return page;
        }
        page.setRecords(customerList);
        return page;
    }

    @Override
    public void syncWwGroup(SyncWwGroupDto syncWwGroupDto) {
        if (syncWwGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (syncWwGroupDto.getDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        String key = RedisCacheKeyEnum.SYNC_GRUOP_DEVICE_GAP.getKey();
        if (redisTemplate.hasKey(key)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "正在同步，请" + DateUtil.convertSecondsToHourMinuteSecond(Math.toIntExact(redisTemplate.getExpire(key, TimeUnit.SECONDS))) + "后再试");
        } else {
            redisTemplate.opsForValue().set(key, true, 300, TimeUnit.SECONDS);
        }
        WwDevice wwDevice = wwDeviceMapper.getById(syncWwGroupDto.getDeviceUniqueId(), syncWwGroupDto.getMerId());
        MicaTriggerConversationPushMsg micaTriggerConversationPushMsg = new MicaTriggerConversationPushMsg();
        micaTriggerConversationPushMsg.setMessageId(IdWorker.getId());
        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerConversationPushMsg, MicaTriggerType.TRIGGER_CONVERSATION_PUSH);
        micaTriggerDto.setMerId(wwDevice.getMerId());
        micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
        micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);

        //设置更新客户群更新时间
        wwDevice.setLastSyncSuctomerGroupTime(DateUtil.getTime());
        wwDeviceMapper.updateWwDevice(wwDevice);
    }


    @Override
    public void batchSyncWwGroup(BatchSyncWwGroupDto batchSyncWwGroupDto) {
        if (batchSyncWwGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchSyncWwGroupDto.getDeviceUniqueIds() == null || batchSyncWwGroupDto.getDeviceUniqueIds().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        for (Long deviceUniqueId : batchSyncWwGroupDto.getDeviceUniqueIds()) {

            try {
                //先查看是否有该机器人的同步通讯录任务记录
                SyncGroupJob syncGroupJob = syncGroupJobMapper.getByDeviceUniqueId(deviceUniqueId, batchSyncWwGroupDto.getMerId());

                if (syncGroupJob == null) {
                    addSyncGroupJob(deviceUniqueId, batchSyncWwGroupDto.getMerId());
                } else {
                    //修改
                    //先判断任务是否未执行或正在执行中
                    if (syncGroupJob.getStatus() == 0 || syncGroupJob.getStatus() == 1) {
                        continue;
                    }
                    updateSyncGroupJob(syncGroupJob);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }


    public void addSyncGroupJob(Long deviceUniqueId, Long merId) {
        SyncGroupJob syncGroupJob = new SyncGroupJob();
        syncGroupJob.setMerId(merId);
        syncGroupJob.setDeviceUniqueId(deviceUniqueId);
        syncGroupJob.setStatus(0);
        syncGroupJob.setJobCreateTime(DateUtil.getTime());
        syncGroupJobMapper.add(syncGroupJob);
    }

    public void updateSyncGroupJob(SyncGroupJob syncGroupJob) {
        syncGroupJob.setStatus(0);
        syncGroupJob.setJobCreateTime(DateUtil.getTime());
        syncGroupJob.setStartTime(null);
        syncGroupJobMapper.update(syncGroupJob);
    }


    @Override
    public Object getSyncGroupList(SyncWwGroupQuery syncWwGroupQuery) {

        if (syncWwGroupQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        //获取机器人ID
        if (!StringUtils.isBlank(syncWwGroupQuery.getKeyword())) {
            WwDeviceQuery wwDeviceQuery = new WwDeviceQuery();
            wwDeviceQuery.setMerId(syncWwGroupQuery.getMerId());
            wwDeviceQuery.setKeyword(syncWwGroupQuery.getKeyword());
            List<WwDeviceVo> wwDeviceVoList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
            if (wwDeviceVoList == null || wwDeviceVoList.isEmpty()) {
                return new MyPageInfo<>(null);
            }
            List<Long> deviceUniqueIds = wwDeviceVoList.stream().map(WwDeviceVo::getId).distinct().collect(Collectors.toList());
            syncWwGroupQuery.setDeviceUniqueIds(deviceUniqueIds);
        }

        String orderBy = OrderByUtil.getOrderBy(syncWwGroupQuery.getOrderByField(), syncWwGroupQuery.isAsc());
        PageHelper.startPage(syncWwGroupQuery.getCurrent(), syncWwGroupQuery.getSize(), orderBy);

        List<SyncGroupJobVo> syncGroupJobVoList = syncGroupJobMapper.getSyncGroupList(syncWwGroupQuery);

        if (syncGroupJobVoList != null && !syncGroupJobVoList.isEmpty()) {
            for (SyncGroupJobVo syncGroupJobVo : syncGroupJobVoList) {
                try {
                    WwDevice wwDevice = wwDeviceMapper.getById(syncGroupJobVo.getDeviceUniqueId(), syncGroupJobVo.getMerId());
                    if (wwDevice != null) {
                        syncGroupJobVo.setDeviceName(wwDevice.getDeviceName());
                        syncGroupJobVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return new MyPageInfo<>(syncGroupJobVoList);
    }


    @Override
    public void delSyncGroup(DelSyncGroupDto delSyncGroupDto) {
        if (delSyncGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (delSyncGroupDto.getIds() == null || delSyncGroupDto.getIds().isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }

        for (Long id : delSyncGroupDto.getIds()) {
            try {
                syncGroupJobMapper.delById(id, delSyncGroupDto.getMerId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    @Override
    @Async("taskExecutor")
    public void excuteSyncGroup(BaseDto baseDto) {
        //获取一开始的任务，如果开始时间距离当前时间超过10分钟，则将状态修改为同步失败
        SyncWwGroupQuery syncWwGroupQuery = new SyncWwGroupQuery();
        Long idStart = 0L;
        syncWwGroupQuery.setMerId(baseDto.getMerId());
        syncWwGroupQuery.setAsc(true);
        syncWwGroupQuery.setCurrent(1);
        syncWwGroupQuery.setSize(50);
        syncWwGroupQuery.setOrderByField("id");
        syncWwGroupQuery.setIdStart(idStart);
        syncWwGroupQuery.setStatus(1);
        String orderBy = OrderByUtil.getOrderBy(syncWwGroupQuery.getOrderByField(), syncWwGroupQuery.isAsc());
        PageHelper.startPage(syncWwGroupQuery.getCurrent(), syncWwGroupQuery.getSize(), orderBy);
        List<SyncGroupJobVo> syncGroupJobVoList = syncGroupJobMapper.getSyncGroupList(syncWwGroupQuery);
        while (syncGroupJobVoList != null && !syncGroupJobVoList.isEmpty()) {
            int nowTime = DateUtil.getTime();
            for (SyncGroupJobVo syncGroupJobVo : syncGroupJobVoList) {
                try {
                    if (syncGroupJobVo.getId().longValue() > idStart.longValue()) {
                        idStart = syncGroupJobVo.getId();
                    }

                    if (nowTime - syncGroupJobVo.getStartTime() > 600) {
                        SyncGroupJob syncGroupJob = syncGroupJobMapper.getById(syncGroupJobVo.getId(), syncGroupJobVo.getMerId());
                        if (syncGroupJob != null) {
                            syncGroupJob.setStatus(3);
                            syncGroupJobMapper.update(syncGroupJob);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            syncWwGroupQuery.setIdStart(idStart);
            PageHelper.startPage(syncWwGroupQuery.getCurrent(), syncWwGroupQuery.getSize(), orderBy);
            syncGroupJobVoList = syncGroupJobMapper.getSyncGroupList(syncWwGroupQuery);
        }

        //获取一个未开始的同步的任务
        SyncGroupJob syncGroupJob = syncGroupJobMapper.getUnSyncGroupTask(baseDto.getMerId());
        if (syncGroupJob != null) {

            WwDevice wwDevice = wwDeviceMapper.getById(syncGroupJob.getDeviceUniqueId(), syncGroupJob.getMerId());
            MicaTriggerConversationPushMsg micaTriggerConversationPushMsg = new MicaTriggerConversationPushMsg();
            micaTriggerConversationPushMsg.setMessageId(IdWorker.getId());
            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerConversationPushMsg, MicaTriggerType.TRIGGER_CONVERSATION_PUSH);
            micaTriggerDto.setMerId(wwDevice.getMerId());
            micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
            micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);

            //设置更新客户群更新时间
            wwDevice.setLastSyncSuctomerGroupTime(DateUtil.getTime());
            wwDeviceMapper.updateWwDevice(wwDevice);

            syncGroupJob.setStatus(1);
            syncGroupJob.setStartTime(DateUtil.getTime());
            syncGroupJobMapper.update(syncGroupJob);
        }

    }

    @Override
    public void syncWwGroupMerber(SyncWwGroupMemberDto syncWwGroupMemberDto) {
        if (syncWwGroupMemberDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (syncWwGroupMemberDto.getDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (syncWwGroupMemberDto.getGroupId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        WwDevice wwDevice = wwDeviceMapper.getById(syncWwGroupMemberDto.getDeviceUniqueId(), syncWwGroupMemberDto.getMerId());
        if (wwDevice == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人不存在");
        }

        WwGroup wwGroup = wwGroupMapper.getById(syncWwGroupMemberDto.getGroupId(), wwDevice.getMerId());
        if (wwGroup == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "群不存在");
        }

        String key = String.format(RedisCacheKeyEnum.SYNC_CUSTOMER_MERBER_GAP.getKey(), syncWwGroupMemberDto.getMerId());
        if (redisTemplate.hasKey(key)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "正在同步，请" + DateUtil.convertSecondsToHourMinuteSecond(Math.toIntExact(redisTemplate.getExpire(key, TimeUnit.SECONDS))) + "后再试");
        } else {
            redisTemplate.opsForValue().set(key, true, 300, TimeUnit.SECONDS);
        }


        MicaTriggerConversationMembersPushMsg micaTriggerConversationMembersPushMsg = new MicaTriggerConversationMembersPushMsg();
        micaTriggerConversationMembersPushMsg.setMessageId(wwGroup.getId());
        micaTriggerConversationMembersPushMsg.setGroupId(wwGroup.getGroupWxid());

        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerConversationMembersPushMsg, MicaTriggerType.TRIGGER_CONVERSATION_MEMBERS_PUSH);
        micaTriggerDto.setMerId(wwDevice.getMerId());
        micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
        micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);

    }

    @Override
    public WwGroup getByGroupId(@MerId Long merId, Long deviceUniqueId, String conversationId) {
        return wwGroupMapper.selectByGroupWxId(merId, deviceUniqueId, conversationId);
    }

    @Override
    public WwGroup getByGroupIdAndDeviceId(@MerId Long merId, String deviceId, String conversationId) {
        return wwGroupMapper.selectByGroupWxIdAndDeviceId(merId, deviceId, conversationId);
    }

    @Override
    public Page<WwGroupMember> listMembersFromChat(RPullGroupMemberMsg content) {

        Long merId = content.getMerId();
        Long talkSessionId = content.getTalkSessionId();
        ChatTalkSession byId = chatTalkSessionService.getById(content.getMerId(), talkSessionId);
        if (Objects.isNull(byId)) {
            throw new BusinessException("会话不存在");
        }
        Page<WwGroupMember> page = new Page<>(content.getCurrent(), content.getSize());
        List<WwGroupMember> wwGroupMembers = groupMemberMapper.pageByGroupId(page, merId, byId.getConversationId(), content.getKeyword());
        page.setRecords(wwGroupMembers);
        return page;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void QuitWwGroup(WwGroupDto wwGroupDto) {
        if (wwGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (wwGroupDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        WwGroup wwGroup = wwGroupMapper.getById(wwGroupDto.getId(), wwGroupDto.getMerId());
        if (wwGroup != null) {
            //
            WwDevice wwDevice = wwDeviceMapper.getById(wwGroup.getDeviceUniqueId(), wwGroup.getMerId());

            WwGroupMember wwGroupMember = wwGroupMemberMapper.getByGroupWxIdAndWxid(wwGroup.getGroupWxid(), wwGroup.getDeviceId(), wwGroup.getMerId());
            if (wwGroupMember != null) {
                wwGroupMemberMapper.deleById(wwGroupMember.getId(), wwGroupMember.getMerId());
                //发送删除群成员指令
                MicaTriggerGroupKickMsg micaTriggerGroupKickMsg = new MicaTriggerGroupKickMsg();
                micaTriggerGroupKickMsg.setMessageId(wwGroupMember.getId());
                micaTriggerGroupKickMsg.setGroupId(wwGroupMember.getGroupWxid());
                micaTriggerGroupKickMsg.setWxIds(wwGroupMember.getWxid());

                MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerGroupKickMsg, MicaTriggerType.TRIGGER_GROUP_KICK);
                micaTriggerDto.setMerId(wwDevice.getMerId());
                micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
                micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
                sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);

            }
            wwGroupMapper.deleById(wwGroup.getId(), wwGroup.getMerId());
            //发送退群指令
            MicaTriggerGroupExitMsg micaTriggerGroupExitMsg = new MicaTriggerGroupExitMsg();
            micaTriggerGroupExitMsg.setMessageId(wwGroup.getId());
            micaTriggerGroupExitMsg.setGroupId(wwGroup.getGroupWxid());

            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerGroupExitMsg, MicaTriggerType.TRIGGER_GROUP_EXIT);
            micaTriggerDto.setMerId(wwDevice.getMerId());
            micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
            micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);


        }

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transferGroupAdmin(TransferGroupAdminDto transferGroupAdminDto) {
        if (transferGroupAdminDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (transferGroupAdminDto.getGroupId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (transferGroupAdminDto.getTransferOutDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (transferGroupAdminDto.getReceiveDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        //判断群主机器人是否存在
        WwDevice wwDevice = wwDeviceMapper.getById(transferGroupAdminDto.getTransferOutDeviceUniqueId(), transferGroupAdminDto.getMerId());
        if (wwDevice == null) {
            return;
        }
        //判断群是否存在
        WwGroup wwGroup = wwGroupMapper.getById(transferGroupAdminDto.getGroupId(), transferGroupAdminDto.getMerId());
        if (wwGroup == null) {
            return;
        }
        //判断转出人是否是群主
        if (!wwDevice.getDeviceId().equals(wwGroup.getCreateWxid())) {
            return;
        }
        //接受的机器人是否是改群中的群成员
        WwDevice wwDeviceReceive = wwDeviceMapper.getById(transferGroupAdminDto.getReceiveDeviceUniqueId(), transferGroupAdminDto.getMerId());
        if (wwDeviceReceive == null) {
            return;
        }
        WwGroupMember wwGroupMember = wwGroupMemberMapper.getByGroupWxIdAndWxid(wwGroup.getGroupWxid(), wwDeviceReceive.getDeviceId(), wwGroup.getMerId());
        if (wwGroupMember == null) {
            return;
        }
        //判断是否是同一企业
        if (!wwDevice.getCorpId().equals(wwDeviceReceive.getCorpId())) {
            return;
        }


        WwGroupQuery wwGroupQuery = new WwGroupQuery();
        wwGroupQuery.setGroupWxids(Arrays.asList(wwGroup.getGroupWxid()));
        wwGroupQuery.setMerId(wwGroup.getMerId());
        List<WwGroupVo> wwGroupList = wwGroupMapper.getWwGroupList(wwGroupQuery);
        if (wwGroupList == null || wwGroupList.isEmpty()) {
            return;
        }

        for (WwGroupVo wwGroupVo : wwGroupList) {
            WwGroup wwGroupUpadte = new WwGroup();
            BeanUtil.copyProperties(wwGroupVo, wwGroupUpadte);
            wwGroupUpadte.setCreateWxid(wwDeviceReceive.getDeviceId());
            wwGroupMapper.updateWwGroup(wwGroupUpadte);
        }


        //发送mq 指令
        MicaTriggerGroupSetOwnerMsg micaTriggerGroupSetOwnerMsg = new MicaTriggerGroupSetOwnerMsg();
        micaTriggerGroupSetOwnerMsg.setMessageId(wwGroup.getId());
        micaTriggerGroupSetOwnerMsg.setGroupId(wwGroup.getGroupWxid());
        micaTriggerGroupSetOwnerMsg.setWxId(wwDeviceReceive.getDeviceId());

        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerGroupSetOwnerMsg, MicaTriggerType.TRIGGER_GROUP_SET_OWNER);
        micaTriggerDto.setMerId(wwDevice.getMerId());
        micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
        micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
        sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addGroupManager(AddGroupManagerDto addGroupManagerDto) {
        if (addGroupManagerDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (addGroupManagerDto.getGroupId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (addGroupManagerDto.getOwnerDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (addGroupManagerDto.getMangerDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        //判断群主机器人是否存在
        WwDevice wwDevice = wwDeviceMapper.getById(addGroupManagerDto.getOwnerDeviceUniqueId(), addGroupManagerDto.getMerId());
        if (wwDevice == null) {
            return;
        }
        //判断群是否存在
        WwGroup wwGroup = wwGroupMapper.getById(addGroupManagerDto.getGroupId(), addGroupManagerDto.getMerId());
        if (wwGroup == null) {
            return;
        }
        //判断转出人是否是群主
        if (!wwDevice.getDeviceId().equals(wwGroup.getCreateWxid())) {
            return;
        }
        //接受的机器人是否是改群中的群成员
        WwDevice wwDeviceManager = wwDeviceMapper.getById(addGroupManagerDto.getMangerDeviceUniqueId(), addGroupManagerDto.getMerId());
        if (wwDeviceManager == null) {
            return;
        }
        WwGroupMember wwGroupMember = wwGroupMemberMapper.getByGroupWxIdAndWxid(wwGroup.getGroupWxid(), wwDeviceManager.getDeviceId(), wwGroup.getMerId());
        if (wwGroupMember == null) {
            return;
        }
        //判断是否是同一企业
        if (!wwDevice.getCorpId().equals(wwDeviceManager.getCorpId())) {
            return;
        }

        WwGroupQuery wwGroupQuery = new WwGroupQuery();
        wwGroupQuery.setGroupWxids(Arrays.asList(wwGroup.getGroupWxid()));
        wwGroupQuery.setMerId(wwGroup.getMerId());
        List<WwGroupVo> wwGroupList = wwGroupMapper.getWwGroupList(wwGroupQuery);
        if (wwGroupList == null || wwGroupList.isEmpty()) {
            return;
        }


        //判断群管理员是否未满三人
        if (!StringUtils.isBlank(wwGroup.getAdminWxIds())) {
            Set<String> wxidList = new HashSet<>();
            for (WwGroupVo wwGroupVo : wwGroupList) {
                ObjectMapper mapper = new ObjectMapper();
                try {
                    Set<String> strings = mapper.readValue(wwGroupVo.getAdminWxIds(), new TypeReference<Set<String>>() {
                    });
                    wxidList.addAll(strings);
                    wxidList.add(wwDeviceManager.getDeviceId());
                    wxidList.remove(wwGroupVo.getCreateWxid());
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                if (wxidList != null && wxidList.size() > 3) {
                    return;
                }

            }

            for (WwGroupVo wwGroupVo : wwGroupList) {
                WwGroup wwGroupUpadte = new WwGroup();
                BeanUtil.copyProperties(wwGroupVo, wwGroupUpadte);
                wwGroupUpadte.setAdminWxIds(JSONObject.toJSONString(wxidList));
                wwGroupMapper.updateWwGroup(wwGroupUpadte);
            }

            //发送mq 指令
            MicaTriggerGroupSetAdminMsg micaTriggerGroupSetAdminMsg = new MicaTriggerGroupSetAdminMsg();
            micaTriggerGroupSetAdminMsg.setMessageId(wwGroup.getId());
            micaTriggerGroupSetAdminMsg.setGroupId(wwGroup.getGroupWxid());
            micaTriggerGroupSetAdminMsg.setWxIds(new ArrayList<>(wxidList));

            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerGroupSetAdminMsg, MicaTriggerType.TRIGGER_GROUP_SET_ADMIN);
            micaTriggerDto.setMerId(wwDevice.getMerId());
            micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
            micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
        }
    }

    @Override
    public Object getReceiveDeviceList(TransferableGroupDto transferableGroupDto) {
        if (transferableGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (transferableGroupDto.getTransferOutDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        //获取群主的机器人
        WwDevice wwDevice = wwDeviceMapper.getById(transferableGroupDto.getTransferOutDeviceUniqueId(), transferableGroupDto.getMerId());
        if (wwDevice == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该机器人");
        }
        //查看该机器人是否是群主的群
        WwGroupQuery wwGroupQuery = new WwGroupQuery();
        wwGroupQuery.setCreateWxid(wwDevice.getDeviceId());
        wwGroupQuery.setMerId(transferableGroupDto.getMerId());
        List<WwGroupVo> wwGroupList = wwGroupMapper.getWwGroupList(wwGroupQuery);
        if (wwGroupList == null || wwGroupList.isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该转出机器人没有所在群主的群");
        }
        List<String> groupWxids = wwGroupList.stream().map(WwGroupVo::getGroupWxid).distinct().collect(Collectors.toList());


        //获取同一个运营商下同一个企业的机器人
        WwDeviceQuery wwDeviceQuery = new WwDeviceQuery();
        wwDeviceQuery.setMerId(transferableGroupDto.getMerId());
        wwDeviceQuery.setCorpId(wwDevice.getCorpId());
        List<WwDeviceVo> wwDeviceList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
        List<WwDeviceVo> filterDeviceList = wwDeviceList.stream().filter(it -> !it.getId().equals(wwDevice.getId())).collect(Collectors.toList());
        if (filterDeviceList == null || filterDeviceList.isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到同一企业下的机器人");
        }

        //获取同一个群下所有机器人成员
        List<String> wxids = filterDeviceList.stream().map(WwDeviceVo::getDeviceId).distinct().collect(Collectors.toList());
        WwGroupMemberQuery wwGroupMemberQuery = new WwGroupMemberQuery();
        wwGroupMemberQuery.setWxids(wxids);
        wwGroupMemberQuery.setMerId(transferableGroupDto.getMerId());
        wwGroupMemberQuery.setGroupWxids(groupWxids);
        List<WwGroupMemberVo> wwGroupMemberList = wwGroupMemberMapper.getWwGroupMemberList(wwGroupMemberQuery);
        if (wwGroupMemberList == null || wwGroupMemberList.isEmpty()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到同一群下的机器人");
        }

        List<String> collect = wwGroupMemberList.stream().map(WwGroupMemberVo::getWxid).distinct().collect(Collectors.toList());
        WwDeviceQuery query = new WwDeviceQuery();
        query.setMerId(transferableGroupDto.getMerId());
        query.setDeviceIds(collect);
        List<WwDeviceVo> deviceList = wwDeviceMapper.getWwDeviceList(query);
        return deviceList;
    }

    @Override
    public Object getTransferableGroup(TransferableGroupDto transferableGroupDto) {
        if (transferableGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (transferableGroupDto.getTransferOutDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(transferableGroupDto.getReceiveDeviceUniqueId() ==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        //判断群主机器人是否存在
        WwDevice wwDevice = wwDeviceMapper.getById(transferableGroupDto.getTransferOutDeviceUniqueId(), transferableGroupDto.getMerId());
        if (wwDevice == null) {
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该群主机器人不存在");
            return null;
        }
        //判断转出人是否是群主
        WwGroupQuery wwGroupQuery=new WwGroupQuery();
        wwGroupQuery.setCreateWxid(wwDevice.getDeviceId());
        wwGroupQuery.setMerId(transferableGroupDto.getMerId());
        List<WwGroupVo> wwGroupList = wwGroupMapper.getWwGroupList(wwGroupQuery);
        if(wwGroupList==null||wwGroupList.isEmpty()){
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该转出机器人没有群");
            return null;
        }
        //接受的机器人是否是改群中的群成员
        WwDevice wwDeviceReceive = wwDeviceMapper.getById(transferableGroupDto.getReceiveDeviceUniqueId(), transferableGroupDto.getMerId());
        if (wwDeviceReceive == null) {
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到接收机器人");
            return null;
        }

        //判断是否是同一企业
        if (!wwDevice.getCorpId().equals(wwDeviceReceive.getCorpId())) {
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "不在同一企业");
            return null;
        }

        //获取是群成员的群
        ArrayList<WwGroupVo>  wwGroupVoArrayList = new ArrayList<>();
        for (WwGroupVo wwGroupVo:wwGroupList) {
            WwGroupMember wwGroupMember = wwGroupMemberMapper.getByGroupWxIdAndWxid(wwGroupVo.getGroupWxid(), wwDeviceReceive.getDeviceId(), wwGroupVo.getMerId());
            if (wwGroupMember != null) {
                wwGroupVoArrayList.add(wwGroupVo);
            }
        }


        if (wwGroupVoArrayList.isEmpty()) {
            return null;

        }

        return new ArrayList<>(wwGroupVoArrayList.stream().collect(Collectors.toMap(WwGroupVo::getGroupWxid, it -> it, (existing, replacement) -> existing)).values());
    }

    @Override
    public Object getManagerableGroup(ManagerableGroupDto managerableGroupDto) {
        if (managerableGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (managerableGroupDto.getOwnerDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(managerableGroupDto.getMangerDeviceUniqueId() ==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        //判断群主机器人是否存在
        WwDevice wwDevice = wwDeviceMapper.getById(managerableGroupDto.getOwnerDeviceUniqueId(), managerableGroupDto.getMerId());
        if (wwDevice == null) {
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该群主机器人不存在");
            return null;
        }
        //判断转出人是否是群主
        WwGroupQuery wwGroupQuery=new WwGroupQuery();
        wwGroupQuery.setCreateWxid(wwDevice.getDeviceId());
        wwGroupQuery.setMerId(managerableGroupDto.getMerId());
        List<WwGroupVo> wwGroupList = wwGroupMapper.getWwGroupList(wwGroupQuery);
        if(wwGroupList==null||wwGroupList.isEmpty()){
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该转出机器人没有群");
            return null;
        }
        //接受的机器人是否是改群中的群成员
        WwDevice wwDeviceReceive = wwDeviceMapper.getById(managerableGroupDto.getMangerDeviceUniqueId(), managerableGroupDto.getMerId());
        if (wwDeviceReceive == null) {
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到接收机器人");
            return null;
        }

        //判断是否是同一企业
        if (!wwDevice.getCorpId().equals(wwDeviceReceive.getCorpId())) {
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "不在同一企业");
            return null;
        }

        //获取群管人数小于3的群，且管理员也在群中的群
        ArrayList<WwGroupVo>  wwGroupVoArrayList = new ArrayList<>();

        for (WwGroupVo wwGroupVo:wwGroupList) {
            if (!StringUtils.isBlank(wwGroupVo.getAdminWxIds())) {
                ObjectMapper mapper = new ObjectMapper();
                List<String> wxidList = null;
                try {
                    wxidList = mapper.readValue(wwGroupVo.getAdminWxIds(), new TypeReference<List<String>>() {});
                } catch (JsonProcessingException e) {
                   e.printStackTrace();
                }

                if (wxidList != null && wxidList.size() < 3) {
                    WwGroupMember wwGroupMember = wwGroupMemberMapper.getByGroupWxIdAndWxid(wwGroupVo.getGroupWxid(), wwDeviceReceive.getDeviceId(), wwGroupVo.getMerId());
                    if (wwGroupMember != null) {
                        wwGroupVoArrayList.add(wwGroupVo);
                    }
                }


            }
        }
        if (wwGroupVoArrayList.isEmpty()) {
            return null;

        }

        return new ArrayList<>(wwGroupVoArrayList.stream().collect(Collectors.toMap(WwGroupVo::getGroupWxid, it -> it, (existing, replacement) -> existing)).values());
    }
}
